# -*- coding: utf-8 -*-
import random
import scrapy
from scrapy import Request
from scrapy.utils.project import get_project_settings
from scrapy.exceptions import IgnoreRequest
from zc_core.spiders.base import BaseSpider
from zc_core.dao.sku_dao import SkuDao
from zc_core.model.items import Box
from zc_core.util.common import get_time_stamp13
from zc_core.util.http_util import retry_request

from ccb.rules import *
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.done_filter import DoneFilter


class FullSpider(BaseSpider):
    name = 'full'
    # 覆盖配置
    custom_settings = {
        'DOWNLOAD_DELAY': 0.3
    }

    # 常用链接
    item_url = 'https://ibuy.ccb.com/mall-basedoc/ware?token={}&wareId={}&mall_type=ORDINARY&timeTap={}'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(FullSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no)

    def start_requests(self):
        # cookies = SeleniumLogin().get_cookies()
        cookies = {'SESSION': '081dd762-af70-4159-929b-50955a6d1ad4'}
        if not cookies:
            self.logger.error('init cookie failed...')
            return
        self.logger.info('init cookie: %s', cookies)
        self.session_id = cookies.get('SESSION', '')

        pool_list = SkuDao().get_batch_sku_list(self.batch_no)
        # pool_list = SkuPoolDao().get_sku_pool_list()
        self.logger.info('全量：%s' % (len(pool_list)))
        random.shuffle(pool_list)
        for sku in pool_list:
            sku_id = sku.get('_id')
            offline_time = sku.get('offlineTime', 0)
            settings = get_project_settings()
            if offline_time > settings.get('MAX_OFFLINE_TIME', 2):
                self.logger.info('忽略: [%s][%s]', sku_id, offline_time)
                continue
            # 避免重复采集
            if self.done_filter.contains(sku_id) and not settings.get('FORCE_RECOVER', False):
                self.logger.info('已采: [%s]', sku_id)
                continue
            # 采集商品
            token_stamp = get_time_stamp13() - 56224
            time_tap = get_time_stamp13()
            yield Request(
                url=self.item_url.format(token_stamp, sku_id, time_tap),
                meta={
                    'reqType': 'item',
                    'batchNo': self.batch_no,
                    'skuId': sku_id,
                },
                headers={
                    'Host': 'ibuy.ccb.com',
                    'Connection': 'keep-alive',
                    'Accept': 'application/json, text/javascript, */*; q=0.01',
                    'Origin': 'https://ibuy.ccb.com',
                    'X-Requested-With': 'XMLHttpRequest',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3861.400 QQBrowser/10.7.4313.400',
                    'Content-Type': 'application/json',
                    'Referer': 'https://ibuy.ccb.com/market/public/ecpage/index/index.html?sessionId={}'.format(
                        self.session_id),
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                },
                cookies=cookies,
                callback=self.parse_item_data,
                errback=self.error_back,
            )

    # 处理ItemData
    def parse_item_data(self, response):
        sku_id = response.meta.get('skuId')
        item_list = parse_item_data(response)
        if item_list:
            self.logger.info('商品: sku=%s, cnt=%s' % (sku_id, len(item_list)))
            yield Box('item', self.batch_no, item_list)
        else:
            self.logger.info('下架: sku=%s' % sku_id)
